package com.kehutong.crm.admin;

import java.util.List;

import org.coraframework.authz.HasPermission;
import org.coraframework.inject.Inject;
import org.coraframework.json.JSONObject;
import org.coraframework.logger.Logger;
import org.coraframework.logger.LoggerFactory;
import org.coraframework.mvc.MvcAction;
import org.coraframework.mvc.http.Bean;
import org.coraframework.mvc.http.ReqMapping;
import org.coraframework.mvc.http.result.Result;
import org.coraframework.orm.Pool;
import org.coraframework.orm.jdbc.JdbcSession;

import com.kehutong.common.DoveClient;
import com.kehutong.common.entity.Root;
import com.kehutong.common.util.Token;
import com.kehutong.crm.entity.Tag;
import com.kehutong.crm.service.TagService;

/**
 * 客户标签控制器
 *
 * @author: liukunlong
 * @date: 2021-02-19 15:12
 */
@MvcAction
@ReqMapping("/admin/crm/tag")
public class TagController {
    
	static final Logger logger = LoggerFactory.getLogger(TagController.class);

    @Inject
    private JdbcSession jdbcSession;

    @Inject
    private TagService tagService;

    @Inject
    private DoveClient doveClient;

    @HasPermission("crm:tag:view")
    @ReqMapping("/tree")
    public Object listParent(JSONObject jsonObject) throws Exception {
        final List<Tag> tagList = jdbcSession.findArray(Tag.class)
                .eq("pid", Root.ROOT_ID)
                .eq("deleted", false)
                .exe();
        Tag root = Pool.newInstance(Tag.class, Root.ROOT_ID);
        root.setName("标签管理");
        root.setChildList(tagList);
        return Result.success(root);
    }

    @HasPermission("crm:tag:view")
    @ReqMapping("/getAllList")
    public Object getAllList(JSONObject jsonObject) {
        final List<Tag> tagList = jdbcSession.findArray(Tag.class)
                .eq("pid", Root.ROOT_ID)
                .eq("deleted", false)
                .exe();

        tagList.forEach(tag -> {
            List<Tag> tags = jdbcSession.findArray(Tag.class)
                    .eq("pid", tag.getId())
                    .eq("deleted", false)
                    .exe();
            tag.setChildList(tags);
        });
        return Result.success(tagList);
    }

    /**
     * 查询后台标签右侧列表
     * 1.如果首次进来(pid==1)查询所有所有数据，如果有条件则进行过滤
     * 2.若果pid!=1则查询符合条件的数据,如果有条件就进行过滤
     * @param jsonObject
     * @return
     * @throws Exception
     */
    @HasPermission("crm:tag:view")
    @ReqMapping("/list")
    public Object list(JSONObject jsonObject) throws Exception {
        String pid = jsonObject.getString("pid");
        if (Root.isRoot(pid)) {
            jsonObject.remove("pid");
        }
        return tagService.getTagList(jsonObject);
       /* return jdbcSession.findPage(Tag.class)
                .noEq("pid", Root.ROOT_ID)
                .eq(jsonObject, "id", "pid")
                .like(jsonObject, "name")
                .eq("deleted", false)
                .order("createTime", "desc")
                .page(jsonObject).exe();*/
    }

    //@HasPermission("crm:tag:view")
    @ReqMapping("/get")
    public Object get(String id) {
        Tag tag = Pool.get(Tag.class, id);
        return Result.success(tag);
    }

    @HasPermission("crm:tag:edit")
    @Bean(newInstance = true, copy = true)
    @ReqMapping("/save")
    public Object save(Token token,Tag tag) throws Exception{
        Object result=tagService.saveTag(tag);
        //如果添加标签组直接返回,否者同步数据到腾讯服务器然后返回
        if (tag.isGroup()) {
            return result;
        }
        Tag syncTag= (Tag) tagService.getTagById(tag.getPid());

       /*
          //内建的才能创建标签同步到企微
          doveClient.post("/wwin-service/tag/wwin/create",(http)-> {
            http.addHeader("companyNo", token.getCompanyNo());
            http.setBody(JSONObject.toJSONString(syncTag));
        });*/
        return Result.success();
    }

    /**
     * 获取标签组编号需要同步的标签组及其标签的数据
     * @param tag 标签组/标签对象
     * @return 标签组及其标签的数据对象
     * @throws Exception 异常
     */
    Tag syncTagGroup(Tag tag) throws Exception{
        boolean isGroup=tag.isGroup();
        String id=isGroup?tag.getId():tag.getPid();
        Tag tagGroup=jdbcSession.findById(Tag.class, id);
        List<Tag> tags = jdbcSession.findArray(Tag.class)
                .eq("pid", tagGroup.getId())
                .eq("deleted", false)
                .exe();
        tagGroup.setChildList(tags);
        return tagGroup;
    }



    @HasPermission("crm:tag:edit")
    @Bean(copy = true)
    @ReqMapping("/update")
    public Object update(Token token,Tag tag) throws Exception {
        return tagService.updateTag(tag);
    }

    @HasPermission("crm:tag:edit")
    @ReqMapping("/delete")
    public Object delete(Token token,Tag tag) throws Exception {
        tagService.deleteTagById(tag.getId());
/*        JSONObject result=doveClient.post("/wwin-service/tag/wwin/delete",(http)-> {
            http.addHeader("companyNo", token.getCompanyNo());
            http.setBody(JSONObject.toJSONString(syncTagGroup(tag)));
        });*/
        return Result.success();
    }
}
